import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userLoginService } from '@/apis/user.js'
import { useCartStore } from './cart'
import { mergeCartData } from '@/apis/cart'
// 存储用户基本信息
export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref({})
    const getUserInfo = async ({ account, password }) => {
      const cartStore = useCartStore()
      const res = await userLoginService({ account, password })
      userInfo.value = res.result
      await mergeCartData(
        cartStore.cartList.map((item) => {
          item.skuId, item.selected, item.count
        })
      )
      cartStore.updateNewList()
    }
    const clearUserInfo = () => {
      const cartStore = useCartStore()
      userInfo.value = {}
      cartStore.clearCart()
    }
    return {
      userInfo,
      getUserInfo,
      clearUserInfo
    }
  },
  {
    persist: true
  }
)
